package com.tianyadu.mmall.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianyadu.mmall.core.common.ResultResponse;
import com.tianyadu.mmall.core.conf.SecurityConstantsConfig;
import com.tianyadu.mmall.core.enums.LoginResponseTypeEnum;
import com.tianyadu.mmall.core.properties.MallSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证授权失败处理器
 *
 * @author xueyj
 * @date 2019-11-04 16:30
 */
@Slf4j
@Component
public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MallSecurityProperties mallSecurityProperties;

    /**
     * 登陆认证失败处理
     * 若认证失败，将响应异常信息写入response
     *
     * @param request   HttpServletRequest
     * @param response  HttpServletResponse
     * @param exception 异常信息
     * @author xueyj
     * @date 2019/11/4-16:53
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败");

        // 判断是用哪一种方式进行登录,如果是JSON，则返回JSON字符串；否则进行页面的跳转
        if (LoginResponseTypeEnum.JSON.equals(mallSecurityProperties.getBrowser().getLoginType())) {
            //   http请求状态码（500）
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            //  设置响应信息的格式及字符编码
            response.setContentType(SecurityConstantsConfig.CONTENT_TYPE_JSON);
            //  将响应异常信息写入至response
            response.getWriter().write(objectMapper.writeValueAsString(ResultResponse.createByErrorMessage(exception.getMessage())));
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}